<?php

/**
 * 短信服务
 *
 */
namespace App\Services;


use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

class AliSmsService2
{
    // 阿里云短信服务的
    private $accessKeyId = "LTAIPQYeKTLNiPUv";
    private $accessSecret = "wHBmEIr1YNp6rNr8zrK9cjFK1gJsLa";

    /**
     * 设置错误提醒
     *
     * 您的渠道 ${mtname} 短时间命中过多，请登录后台检查设置情况
     *
     * @param $phone
     * @param $channel
     *
     * @return bool
     */
    public function sendWhiteNotifySms($phone, $channel)
    {
        $templateCode = "SMS_183760833";
        // 修改密码验证码短信
        $templateParam = json_encode(["mtname" => $channel]);
        $resultCode = $this->sendSms("正能科技", $templateCode, $templateParam, ltrim($phone, "86"));

        return $resultCode == "OK";
    }


    /**
     * 发送单条短信
     *
     * @param $signName 签名
     * @param $templateCode 短信模板CODE
     * @param $templateParam 短信模板参数
     * @param $phoneNumbers 收短信码人
     * @return mixed|string
     */
    private function sendSms($signName, $templateCode, $templateParam, $phoneNumbers)
    {
        try {
            AlibabaCloud::accessKeyClient($this->accessKeyId, $this->accessSecret)
                ->regionId('us-east-1')
                ->asDefaultClient();

            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => "us-east-1", //cn-hangzhou
                        "SignName" => $signName,
                        "TemplateCode" => $templateCode,
                        "TemplateParam" => $templateParam,
                        "PhoneNumbers" => $phoneNumbers,
                        //"SmsUpExtendCode" => "1001",
                    ],
                ])
                ->request();

            \Log::info($result);

            if ($result["Code"] != "OK") {
                \Log::info("********");
                \Log::info([$templateCode, $templateParam, $phoneNumbers]);
                \Log::info("********");
            }

            return $result["Code"];
        } catch (ClientException $e) {
            \Log::error($e->getErrorMessage());
        } catch (ServerException $e) {
            \Log::error($e->getErrorMessage());
        }

        return "ERROR";
    }
}
